// 引入axios的核心库
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import qsString from 'querystring'

// 引入接口
import { ResultDate } from './interface'

let config = {
    baseURL: '/api'
}

// 通过类去进行拦截器以及交互方法的封装
class HttpRequest {
    http: AxiosInstance
    // 类的作用域
    constructor(config: AxiosRequestConfig) {
        this.http = axios.create(config)
        this.http.interceptors.request.use(req => req)
        this.http.interceptors.response.use((res: AxiosResponse) => res)
    }

    // get方法
    get<T>(url: string, params?: object): Promise<ResultDate<T>> {
        return this.http.get(url, { params })
    }
    // post方法
    post<T>(url: string, params?: any, isFile: boolean = false): Promise<ResultDate<T>> {
        let data: any = {}
        if (isFile) {
            data = new FormData()
            for (const [i, value] of Object.entries(params)) {
                data.append(i, value)
            }
        } else {
            data = qsString.stringify(params)
        }
        return this.http.post(url, data)
    }
}

// 导出实例化结果
export default new HttpRequest(config)